/**
 * 
 */
package com.lehecai.core.lottery.fetcher.jclq.impl;

import com.lehecai.core.exception.UnsupportedFetcherTypeException;
import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.FetcherType;
import com.lehecai.core.lottery.fetcher.jclq.IJclqDynamicInstantSpFetcher;
import com.lehecai.core.lottery.fetcher.jclq.JclqDynamicInstantSpItem;
import com.lehecai.core.util.CoreObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 基础竞彩篮球sp抓取，抽象，待具体实现
 *
 */
public abstract class BaseJclqDynamicInstantSpFetcher implements IJclqDynamicInstantSpFetcher {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @SuppressWarnings("unchecked")
    @Override
    public List<JclqDynamicInstantSpItem> fetch(String phaseNo, FetcherType fetcherType, LotteryType lotteryType, String terminalId) throws UnsupportedFetcherTypeException {
   		if (fetcherType.getValue() == FetcherType.T_DEFAULT.getValue()) {
			return fetch(phaseNo, getDefaultFetcherType(), lotteryType);
		}
        boolean terminalIdParamter = false;
		Method m;
		try {
			m = CoreObjectUtils.getMethod(getClass(), "fetch" + fetcherType.getName(), new Class[]{String.class, LotteryType.class, String.class});
            terminalIdParamter = true;
		} catch (SecurityException e) {
			m = null;
			logger.error(e.getMessage(), e);
		} catch (NoSuchMethodException e) {
            // 尝试查找没有terminalId的方法
            try {
                m = CoreObjectUtils.getMethod(getClass(), "fetch" + fetcherType.getName(), new Class[]{String.class, LotteryType.class});
            } catch (SecurityException ex) {
                m = null;
                logger.error(e.getMessage(), e);
            } catch (NoSuchMethodException ex) {
                logger.error("未找到({})的抓取器", fetcherType.getName());
                throw new UnsupportedFetcherTypeException("未找到抓取器");
            }
		}
		if (m == null) {
			return null;
		}
		Object[] o;
        if (terminalIdParamter) {
            o = new Object[]{phaseNo, lotteryType, terminalId};
        } else {
            o = new Object[]{phaseNo, lotteryType};
        }
		try {
			return (List<JclqDynamicInstantSpItem>) m.invoke(this, o);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	@Override
	public List<JclqDynamicInstantSpItem> fetch(String phaseNo, LotteryType lotteryType) throws UnsupportedFetcherTypeException{
		return fetch(phaseNo, getDefaultFetcherType(), lotteryType, null);
	}
	
	public List<JclqDynamicInstantSpItem> fetch(String phaseNo, FetcherType fetcherType, LotteryType lotteryType) throws UnsupportedFetcherTypeException{
		return fetch(phaseNo, fetcherType, lotteryType, null);
	}
	
	/**
	 * 获取默认抓取类型
	 * @return
	 */
	abstract protected FetcherType getDefaultFetcherType();
}
